import { Service } from "egg";
import { UserProps } from "../model/User";
import { ObjectId } from "mongoose";
import { defaultIndexCondition, IndexCondition } from "../common";
export interface CreateCompanyProps {
  phoneNumber: string;
  company_name: string;
  password: string;
  nikeName: string;
  role: [];
  [key: string]: any;
}
export interface CreateUserProps {
  phoneNumber: string;
  password: string;
  nikeName: string;
  company: ObjectId;
  role: [];
  [key: string]: any;
}

export default class UserService extends Service {
  /**
   * 根据传入名称查询
   */
  public findByName(condition) {
    return this.ctx.model.User.findOne(condition);
  }

  /**
   * 查找列表
   */
  public async findList(condition: IndexCondition) {
    const { ctx } = this;
    const _condition = { ...defaultIndexCondition, ...condition };
    const { pageIndex, pageSize, select, populate, customSort, find } =
      _condition;
    const skip = pageIndex * pageSize;
    const res = await ctx.model.User.find(find && find)
      .select(select)
      .populate(populate)
      .skip(skip)
      .limit(pageSize)
      .sort(customSort)
      .lean();
    const count = await ctx.model.User.find(find && find).count();
    return { count, list: res, pageSize, pageIndex: pageIndex + 1 };
  }

  /**
   * 公司人员添加数据
   * @param data 参数
   */
  public async add(data: CreateUserProps) {
    const { ctx } = this;
    // TODO 暂时写死公司ID，后续需要从ctx.state.user获取
    const { company } = ctx.state.user;
    const { phoneNumber, password, nikeName, role } = data;
    const hash = await ctx.genHash(password);
    const _data: Partial<UserProps> = {
      phoneNumber,
      company,
      nikeName,
      role,
      ...{ password: hash },
    };
    return await ctx.model.User.create(_data);
  }

  /**
   * 发送手机验证码
   * @param phoneNumber 手机号
   * @param veriCode 随机生成的验证码
   */
  public async sendSMS(phoneNumber: string, veriCode: string) {
    // const {app} = this;
    // const sendSmsRequest = new $Dysmsapi.SendSmsRequest({
    //   phoneNumbers: phoneNumber,
    //   signName: "今晚打老虎",
    //   templateCode: "SMS_232173611",
    //   templateParam: `{\"code\":\"${veriCode}\"}`,
    // })
    // return await app.ALClient.sendSms(sendSmsRequest);
    return {
      body: {
        code: "OK",
      },
      value: {
        phoneNumber,
        veriCode,
      },
    };
  }

  /**
   * 公司注册
   * @param data 注册数据
   */
  public async orgRegister(data: CreateCompanyProps) {
    const { ctx, app } = this;
    const { phoneNumber, company_name, nikeName, password } = data;
    // 开启事务
    const _session = await app.mongoose.startSession();
    _session.startTransaction();
    try {
      // 添加公司
      const _company = await ctx.model.Company.create([{ company_name }], {
        session: _session,
        new: true,
      });
      // 添加人员并赋值角色
      const _hashPassword = await ctx.genHash(password);
      const _person = await ctx.model.User.create(
        [
          {
            phoneNumber,
            nikeName,
            password: _hashPassword,
            role: data.role,
            company: _company[0]._id,
          },
        ],
        { session: _session, new: true }
      );
      await _session.commitTransaction();
      _session.endSession();
      // 注册成功后，相当于直接就登录了，所以这里需反馈token
      const token = app.jwt.sign(
        {
          name: _person[0].nikeName,
          _id: _person[0]._id,
          company: _company[0]._id,
          role: data.role,
        },
        app.config.jwt.secret
      );
      return { token };
    } catch (e) {
      await _session.abortTransaction();
      _session.endSession();
      return false;
    }
  }
}
